package com.aliyun.heiyu.powermaster.server.dao;

import com.aliyun.heiyu.common.source.ConnectionManager;
import com.aliyun.heiyu.powermaster.server.annotation.Transactional;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

public class TransactionProxy implements InvocationHandler {
    private Object target;

    public TransactionProxy(Object target){
        this.target = target;
    }

    public <T> T getProxy(){
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),
            target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Method originalMethod = target.getClass().getMethod(method.getName(), method.getParameterTypes());
        if(!originalMethod.isAnnotationPresent(Transactional.class)){
            return method.invoke(target,args);
        }
        Object result = null;
        Connection conn = ConnectionManager.getInstance().getConnection();
        try {
            ConnectionManager.getInstance().beginTransaction(conn);
            //调用原始业务对象的业务方法
            result = method.invoke(target, args);
            ConnectionManager.getInstance().commit(conn);
        } catch (Throwable t) {
            ConnectionManager.getInstance().rollback(conn);
            throw t;
        } finally {
            if(null != conn){
                ConnectionManager.getInstance().close(conn);
            }
        }

        return result;
    }
}
